import { transformCount, timeTransformData, transformTime1 } from '@/utils/util'
import { getSongDetailList } from '@/api/playLists/index'

interface Playlist {
  picUrl: string;
  name: string;
  copywriter: string;
  playCount: string;
  id: number;
  nickname: string;
  userId: number;
  tag: string;
  updateTime: number;
  [params: string]: any
}

export const translatePlaylist = (res) => {
  const { data: { playlists, total } } = res
  if (res && playlists.length) {
    const playlistArr = playlists.map(item => ({
      picUrl: item.coverImgUrl,
      copywriter: item.copywriter,
      name: item.name,
      id: item.id,
      playCount: transformCount(item.playCount),
      nickname: item.creator.nickname,
      userId: item.creator.userId,
      updateTime: item.updateTime,
      tag: item.tag
    } as Playlist))
    return {
      playlists: playlistArr,
      total
    }
  } else {
    return {
      playlists: [],
      total: 0
    }
  }
}

export const transSongDetailList = (res) => {
  const { data: { songs } } = res
  if (res && songs.length) {
    return songs.map(item => {
      const { id, name, al: { id: alId, name: alName }, ar, mv, dt } = item
      const artists = ar.map(item => ({ id: item.id, name: item.name }))
      const duration = transformTime1(dt)
      return {
        id,
        name,
        alId,
        alName,
        artists,
        duration,
        mv
      } as PlaylistSongDetail
    })
  } else {
    return []
  }
}

export const transPlaylistDetail = async (res) => {
  const { data: { playlist } } = res
  if (res && playlist) {
    const { id, name, coverImgUrl, creator, createTime: time, description: desc, playCount: count, shareCount, subscribedCount, commentCount, tags, trackCount, trackIds, tracks } = playlist
    const { userId, nickname, avatarUrl } = creator
    const playCount = transformCount(count)
    const createTime = timeTransformData(time)
    const subDescription = desc ? desc.split('\n')[0] : ''
    const description = desc ? desc.split('\n').splice(1).join('\n') : ''
    // 只能获取十条歌曲信息
    /* const songs = tracks.map(item => {
      const { id, name, al: { id: alId, name: alName }, ar, mv, dt } = item
      const artists = ar.map(item => ({ id: item.id, name: item.name }))
      const duration = transformTime1(dt)
      return {
        id,
        name,
        alId,
        alName,
        artists,
        duration,
        mv
      } as PlaylistSongDetail
    }) */
    const ids = trackIds.map(item => item.id).join(',')
    const songs = await getSongDetailList(ids)
    return {
      id,
      name,
      coverImgUrl,
      userId,
      nickname,
      avatarUrl,
      tags,
      playCount,
      subscribedCount,
      shareCount,
      trackCount,
      commentCount,
      createTime,
      subDescription,
      description,
      songs
    } as PlaylistDetail
  }
}
